package com.kipling.jfinal.plugin.ioc.core;

import java.lang.reflect.Field;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.core.ControllerFactory;
import com.kipling.jfinal.plugin.ioc.annotation.JFAutowired;

/**
 * 生成Controller实现依赖注入
 * @author kipling
 *
 */
public class IocControllerFactory extends ControllerFactory {
	
	@Override
	public Controller getController(Class<? extends Controller> controllerClass)
			throws InstantiationException, IllegalAccessException {
		Controller  controller = controllerClass.newInstance();
		Field[] beanFields =controller.getClass().getDeclaredFields();
		try {
			Map<Class<?>, Object> beanMap = BeanLoader.getBeanMap();
			for (Field beanField : beanFields) {
				// 判断当前 Bean 字段是否带有 JFAutowired 注解
	            if (beanField.isAnnotationPresent(JFAutowired.class)) {
	            	// 获取 Bean 字段对应的类
	                Class<?> implementClass = beanField.getType();
	                // 若存在实现类，则执行以下代码
	                if (implementClass != null) {
	                    // 从 Bean Map 中获取该实现类对应的实现类实例
	                    Object implementInstance = beanMap.get(implementClass);
	                    // 设置该 Bean 字段的值
	                    if (implementInstance != null) {
	                        beanField.setAccessible(true); // 将字段设置为 public
	                        beanField.set(controller, implementInstance); // 设置字段初始值
	                    } else {
	                        throw new RuntimeException("依赖注入失败！类名：" + controller.getClass().getSimpleName() + "，字段名：" + implementClass.getSimpleName());
	                    }
	                }
	            }
			}
		}catch (Exception e) {
            throw new RuntimeException("初始化 IocControllerFactory 出错！", e);
        }	

		return controller;
	}

}
